package com.hyh.admin.recommend;

import com.hyh.ad.common.core.controller.BaseController;
import com.hyh.ad.common.core.domain.AjaxResult;
import com.hyh.ad.common.utils.SecurityUtils;
import com.hyh.admin.domain.resources.Resources;
import com.hyh.admin.service.IResourcesService;
import com.hyh.admin.sys.mapper.SysUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/recommend")
@Api(tags = "推荐管理")
public class RecommendController extends BaseController {

    @Autowired
    private ItemBasedCFRecommendationService itemBasedCFRecommendationService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private UserProfileService userProfileService;

    @Autowired
    private IResourcesService resourcesService;


    @GetMapping("/list")
    @ApiOperation(value = "查询推荐列表")
    public AjaxResult list() {
        // 获取所有的用户画像
        List<UserProfile> existingUsers = new ArrayList<>();

        // 获取自己的用户画像
        UserProfile userProfilePerson = userProfileService.getUserProfile(SecurityUtils.getLoginUser().getUser().getId().toString());

        // 获取当前用户 ID
        String currentUserId = SecurityUtils.getLoginUser().getUser().getId().toString();

        // 查询所有的用户画像（排除自己）
        sysUserMapper.selectList(null).forEach(user -> {
            if (!user.getId().toString().equals(currentUserId)) { // 过滤掉自己
                UserProfile userProfileCanvas = userProfileService.getUserProfile(user.getId().toString());
                if (userProfileCanvas != null) { // 防止空数据
                    existingUsers.add(userProfileCanvas);
                }
            }
        });


        // 用户-课程评分数据
        Map<String, Map<String, Double>> userRatings = new HashMap<>();
        for (UserProfile userProfile : existingUsers) {
            if (userProfile.getRatedCourses() != null) {
                userRatings.put(userProfile.getUser().getId().toString(), userProfile.getRatedCourses());
            }
        }

        // 计算课程相似度
        Map<String, Map<String, Double>> courseSimilarity = itemBasedCFRecommendationService.computeCourseSimilarity(userRatings);
        logger.info("用户评分矩阵: {}", userRatings);
        logger.info("课程相似度矩阵{}", courseSimilarity);

        // 获取推荐列表
        Map<String, Double> recommendMap = itemBasedCFRecommendationService.predictUserRatings(
                SecurityUtils.getLoginUser().getUser().getId().toString(), userRatings, courseSimilarity);
        logger.info("推荐列表{}", recommendMap);

        // 1. 获取用户画像中的评分数据
        Map<String, Double> ratedCourses = userProfilePerson.getRatedCourses();
            if (ratedCourses.isEmpty()) {
            //ratedCourses = new HashMap<>();
            List<Resources> resources = resourcesService.selectResourcesByIds(userProfilePerson.getRecommendedCourses().toArray(new String[0]));
            return AjaxResult.success( resources);
        }

        // 2. 合并推荐评分和用户已有评分（已有评分优先）
        for (Map.Entry<String, Double> entry : recommendMap.entrySet()) {
            ratedCourses.putIfAbsent(entry.getKey(), entry.getValue());
        }


        // 3. 排序课程（按评分降序）
        List<Map.Entry<String, Double>> sortedCourses = ratedCourses.entrySet()
                .stream()
                .sorted((e1, e2) -> Double.compare(e2.getValue(), e1.getValue())) // 降序
                .collect(Collectors.toList());

        logger.info("sortedCourses: {}", sortedCourses);
        // 5. 获取课程信息
        List<Resources> resources = resourcesService.selectResourcesByIds(sortedCourses.stream()
                .map(Map.Entry::getKey).toArray(String[]::new));

        // 6. 更新用户画像（保存合并后的评分数据）
        userProfilePerson.setRatedCourses(ratedCourses);

        userProfileService.saveUserProfile(userProfilePerson);
        List<String> recommendedCourses = userProfilePerson.getRecommendedCourses();
        if (recommendedCourses != null && !recommendedCourses.isEmpty()) {
            List<Resources> resources1 = resourcesService.selectResourcesByIds(recommendedCourses.toArray(new String[0]));
            // 使用 Set 去重，防止资源重复
            Set<Resources> resourceSet = new HashSet<>(resources);
            resourceSet.addAll(resources1);
            resources = new ArrayList<>(resourceSet);
        }

        return AjaxResult.success(resources);
    }
}
